/**
 * Created by andy on 2017/4/26.
 */
export var Ecg = {
  oEcg: undefined,
  ecgData: [],
  nvData: [],
  unit: 5,
  ppdw: 0, //1小格的像素值
  hSplitBigNum: 1,
  startBigGridHNum: 0, //心电图曲线起始的垂直大格数
  startBigGridWNum: 0, //心电图曲线起始的大格数
  ecgGridWNum: 0, //心电图曲线的水平格子数
  ecgGridHNum: 0, //心电图曲线的垂直格子数
  bigGridWNum: 0, //总共的水平大格子数
  bigGridHNum: 0, //总共的垂直大格子数
  totalWidth: 1027, //心电图的总宽度
  totalHeight: 500, //心电图的总高度
  gridLen: 0,
  end_x: 0,
  end_y: 0,
  js_getDPI: function() {
    var arrDPI = []
    if (window.screen.deviceXDPI) {
      arrDPI[0] = window.screen.deviceXDPI
      arrDPI[1] = window.screen.deviceYDPI
    } else {
      var tmpNode = document.createElement('DIV')
      tmpNode.style.cssText = 'width:1in;height:1in;position:absolute;left:0px;top:0px;z-index:99;visibility:hidden'
      document.body.appendChild(tmpNode)
      arrDPI[0] = parseInt(tmpNode.offsetWidth)
      arrDPI[1] = parseInt(tmpNode.offsetHeight)
      tmpNode.parentNode.removeChild(tmpNode)
    }
    return arrDPI
  },
  getDpi: function() {
    return this.js_getDPI()
  },
  /**
         * 设置基本参数
         * @param ppdw 1小格的像素值
         * @param startBigGridHNum 心电图曲线起始的垂直大格数
         * @param startBigGridWNum 心电图曲线起始的大格数
         * @param ecgGridHNum 心电图曲线的垂直格子数
         * @param ecgGridWNum 心电图曲线的水平格子数
         * @param bigGridHNum 总共的垂直大格子数
         * @param bigGridWNum 总共的水平大格子数
         * @param totalHeight 心电图的总高度
         * @param totalWidth  心电图的总宽度
         */
  setParam: function(ppdw, startBigGridHNum, startBigGridWNum, ecgGridHNum, ecgGridWNum, bigGridHNum, bigGridWNum, totalHeight, totalWidth) {
    this.ppdw = ppdw
    this.startBigGridHNum = startBigGridHNum
    this.startBigGridWNum = startBigGridWNum
    this.ecgGridWNum = ecgGridWNum
    this.ecgGridHNum = ecgGridHNum
    this.bigGridWNum = bigGridWNum
    this.bigGridHNum = bigGridHNum
    this.totalHeight = totalHeight
    this.totalWidth = totalWidth
    this.gridLen = this.unit * this.ppdw
    this.end_x = this.bigGridWNum * this.gridLen
    this.end_y = this.bigGridHNum * this.gridLen

  },
        
  clear: function() {
    this.oEcg.innerHTML = ''
  },
        
  /**
         *
         * @param oEcg svg对象  document.getElementById('ecg')
         * @param parentDivArray 父类Div编号，可能是多个，可以调整父及div的宽度和高度
         */
  init: function(oEcg, parentDivArray) {
    this.oEcg = oEcg
    var dpiArray = this.getDpi()
    var dpi = dpiArray[0] //按照打印的dpi来算的
    // var screenHeight = window.screen.height
    // var screenWidth = window.screen.width
    var startBigGridHNum = 2
    var startBigGridWNum = 4
    var offsetBigGridWNum = 4
    var offsetBigGridHNum = 1
    var ecgGridWNum = 50
    var ecgGridHNum = 24
    var bigGridWNum = ecgGridWNum + startBigGridWNum + offsetBigGridWNum
    var bigGridHNum = ecgGridHNum + startBigGridHNum + offsetBigGridHNum + this.hSplitBigNum * 6
    var smallGridWNum = bigGridWNum * this.unit
    var smallGridHNum = bigGridHNum * this.unit
    // var inch = Math.sqrt(screenWidth * screenWidth + screenHeight * screenHeight) / dpi
    var ppdw = dpi / 25.4
    // var ppdw = 1 / (Math.sqrt(screenWidth * screenWidth + screenHeight * screenHeight) / dpi / 25.4);
    var totalHeight = ppdw * smallGridHNum
    var totalWidth = ppdw * smallGridWNum

    oEcg.style.height = totalHeight
    oEcg.style.width = totalWidth
    if (parentDivArray) {
      var len = parentDivArray.length
      for (var j = 0; j < len; j++) {
        
        var parentDivObj = document.getElementById(parentDivArray[j])
        if (parentDivObj) {
          parentDivObj.style.height = totalHeight + 'px'
          parentDivObj.style.width = totalWidth + 'px'
        }
      }
    }

    this.setParam(ppdw, startBigGridHNum, startBigGridWNum, ecgGridHNum, ecgGridWNum, bigGridHNum, bigGridWNum, totalHeight, totalWidth)
  },
        
  drawGrid: function() {
    // var unit = this.ppdw * this.unit
    // var strokeWidth = this.ppdw * 0.1
    // this.drawUnitLinePoint(1, "#000", strokeWidth, 5);
    this.drawUnitGrid(1, '#f1dedf', 1, 5, '')
    this.drawUnitGrid(5, '#f0adaa', 1, 0, '')
    this.drawOutGrid('#f0adaa', 1)
    // this.drawUnitLinePoint(this.unit, '#000', strokeWidth, 0, strokeArray2);
    // this.drawUnitGrid(10, '#e0514b', 0.5, '');
  },
  drawTimeLine: function(stroke, strokeWidth) {
    var x1 = this.startBigGridWNum * this.gridLen
    // var total_y = this.end_y
    var y1 = this.end_y - this.ppdw
    var x2 = this.end_x
    var y2 = y1
    this.drawLine(x1, y1, x2, y2, stroke, strokeWidth)
    var oneSecLen = 5 * this.gridLen
    // var lineArray = []
    for (var i = 0; i <= 10; i++) {
      var xi1 = x1 + i * oneSecLen
      var yi1 = y1 - this.ppdw
      var xi2 = xi1
      var yi2 = y1 + this.ppdw
      this.drawLine(xi1, yi1, xi2, yi2, stroke, strokeWidth)
      var labelX = xi1 - this.ppdw * 2
      var labelY = yi1 - this.ppdw * 2
      this.drawLabel(labelX, labelY, 'black', 'time_' + i, i + 's')
    }
  },
        
  line: function(x1, y1, x2, y2) {
    function LineObj(x1, y1, x2, y2) {
      this.x1 = x1
      this.y1 = y1
      this.x2 = x2
      this.y2 = y2
      return this
    }

    return new LineObj(x1, y1, x2, y2)
  },
        
  /**
         * 画线
         * @param x1
         * @param y1
         * @param x2
         * @param y2
         * @param stroke
         * @param strokeWidth
         * @param strokeDashArray
         */
  drawLine: function(x1, y1, x2, y2, stroke, strokeWidth, strokeDashArray) {
    var oLine = document.createElementNS('http://www.w3.org/2000/svg', 'line')
    oLine.setAttribute('x1', x1)
    oLine.setAttribute('y1', y1)
    oLine.setAttribute('x2', x2)
    oLine.setAttribute('y2', y2)
    oLine.style.stroke = stroke
    oLine.style.strokeWidth = strokeWidth
    if (strokeDashArray && strokeDashArray != '') {
      oLine.setAttribute('stroke-dasharray', strokeDashArray)
    }
    this.oEcg.appendChild(oLine)
  },
  drawPoint: function(cx, cy, r, stroke, strokeWidth, fill) {
    var oPoint = document.createElementNS('http://www.w3.org/2000/svg', 'circle')
    oPoint.setAttribute('cx', cx)
    oPoint.setAttribute('cy', cy)
    oPoint.setAttribute('r', r)
    oPoint.setAttribute('fill', fill)
    oPoint.style.stroke = stroke
    oPoint.style.strokeWidth = strokeWidth
    this.oEcg.appendChild(oPoint)
  },
  drawUnitLinePoint: function(sepGridNum, stroke, strokeWidth, notGridUnit) {
    var splitGrid = this.ppdw * sepGridNum
    var notGrid = notGridUnit * this.ppdw
    for (let x = 0; x < this.end_x; x += splitGrid) {
      if (x % notGrid !== 0) {
        for (let y = 0; y < this.end_y; y += splitGrid) {
          if (y % notGrid !== 0) {
            this.drawPoint(x, y, strokeWidth, stroke, strokeWidth, 'black')
          }
        }
      }
    }
    for (let y = 0; y < this.end_y; y += notGrid) {
      for (let x = 0; x < this.end_x; x += splitGrid / 2) {
        if (x % splitGrid !== 0) {
          this.drawPoint(x, y, strokeWidth, stroke, strokeWidth, 'black')
        }
      }
    }
    for (let x = 0; x < this.end_x; x += notGrid) {
      for (let y = 0; y < this.end_y; y += splitGrid / 2) {
        if (y % splitGrid !== 0) {
          this.drawPoint(x, y, strokeWidth, stroke, strokeWidth, 'black')
        }
      }
    }
  },
  drawOutGrid: function(stroke, strokeWidth) {
    this.drawLine(0, 0, 0, this.end_y, stroke, strokeWidth)
    this.drawLine(0, 0, this.end_x, 0, stroke, strokeWidth)
    this.drawLine(this.end_x, 0, this.end_x, this.end_y, stroke, strokeWidth)
    this.drawLine(0, this.end_y, this.end_x, this.end_y, stroke, strokeWidth)
  },

  /**
         * 画单元格
         * @param sepGridNum 中间间隔的小个子数
         * @param stroke
         * @param strokeWidth
         * @param notGridUnit
         * @param strokeDashArray
         */
  drawUnitGrid: function(sepGridNum, stroke, strokeWidth, notGridUnit, strokeDashArray) {
    var splitGrid = this.ppdw * sepGridNum
    var end_y = this.end_y
    var end_x = this.end_x
    var i = 0
    for (var x = 0; x < end_x; x += splitGrid) {
      if (notGridUnit > 0 && (i % (notGridUnit) == 0)) { // eslint-disable-line
        // console.log('1')
      } else {
        this.drawLine(x, 0, x, end_y, stroke, strokeWidth, strokeDashArray)
      }
      i++
    }

    i = 0
    for (var y = 0; y < end_y; y += splitGrid) {
      if (notGridUnit > 0 && (i % (notGridUnit) == 0)) { // eslint-disable-line
        // console.log('2')
      } else {
        this.drawLine(0, y, end_x, y, stroke, strokeWidth, strokeDashArray)
      }
      i++
    }
  },
        
  /**
         * 画标准高度
         * @param stroke
         * @param strokeWidth
         */
  drawSetStart: function(stroke, strokeWidth) {
    var array = []
    var ppdm = this.ppdw
    var startSmallGridHNum = this.startBigGridHNum * this.unit
    var startSmallGridWNum = this.startBigGridWNum * this.unit
    // console.log("startSmallGridWNum:" + startSmallGridWNum)
    for (var i = 0; i < 6; i++) {
      var x1 = (startSmallGridWNum - 4) * ppdm
      var y1 = i * ppdm * this.unit * 4 + startSmallGridHNum * ppdm + this.hSplitBigNum * this.gridLen * (i + 1) + this.unit * 2 * ppdm
      var x2 = x1 + 1 * ppdm
      var y2 = y1
      var x3 = x2
      var y3 = y1 - ppdm * this.unit * 2
      var x4 = x3 + 2 * ppdm
      var y4 = y3
      var x5 = x4
      var y5 = y2
      var x6 = x5 + 1 * ppdm
      var y6 = y2
      array.push(this.line(x1, y1, x2, y2))
      array.push(this.line(x2, y2, x3, y3))
      array.push(this.line(x3, y3, x4, y4))
      array.push(this.line(x4, y4, x5, y5))
      array.push(this.line(x5, y5, x6, y6))
    }
    // console.log(array)
    this.drawLineList(array, stroke, strokeWidth)
  },
        
  /**
         * 画多条线
         * @param line_array
         * @param stroke
         * @param strokeWidth
         */
  drawLineList: function(line_array, stroke, strokeWidth) {
    var len = line_array.length
    for (var j = 0; j < len; j++) {
      this.drawLine(line_array[j].x1, line_array[j].y1, line_array[j].x2, line_array[j].y2, stroke, strokeWidth, '')
    }
  },
        
  /**
         * 画文本
         * @param x 横坐标
         * @param y 纵坐标
         * @param fill 填充的颜色
         * @param divId 对应的div编号，便于获取
         * @param val 文本值
         */
  drawLabel: function(x, y, fill, divId, val) {
    var textR1 = document.createElementNS('http://www.w3.org/2000/svg', 'text')
    textR1.setAttribute('x', x + 'px')
    textR1.setAttribute('y', y + 'px')
    textR1.setAttribute('fill', fill)
    textR1.setAttribute('font-size', '12px')
    textR1.id = divId
    var textRData1 = document.createTextNode(val)
    textR1.appendChild(textRData1)
    this.oEcg.appendChild(textR1)
  },
        
  drawTitle: function(data) {
    var start = this.startBigGridWNum * this.gridLen
    this.drawLabel(start, 20, 'black', 'report_start_time', data.report_start_time)
    this.drawLabel(start + 200, 20, 'black', 'report_user', data.report_user)
    this.drawLabel(start + 360, 20, 'black', 'report_sex', data.report_sex)
    this.drawLabel(start + 450, 20, 'black', 'report_age', data.report_age)
    this.drawLabel(start + 530, 20, 'black', 'report_hr', data.report_hr)
    this.drawLabel(start + 700, 20, 'black', 'report_id', data.report_id)
  },
        
  /**
         *  画心电图曲线
         * @param ecgData [-29, -26, -22, -29, -59, -73, -88, -103, -88, -77, -73, -51, -44, -73,....]心电电压值
         * @param start_time 检测开始时间
         * @param sample 采样率
         */
  drawData: function(ecgData, start_time, sample) {
    //1分钟
    var result = []
    //每行有多少个点
    //10秒一行
    var perLineCount = sample * 10
    for (var i = 0, len = ecgData.length; i < len; i += perLineCount) {
      result.push(ecgData.slice(i, i + perLineCount))
    }
    var startXGrid = this.gridLen * this.startBigGridWNum
    var xGridPerPoint = this.ecgGridWNum * this.gridLen / perLineCount
    // console.log(this.bigGridWNum * this.unit * this.ppdw);
    for (var j = 0; j < result.length; j++) {
      var arr = result[j]
      var point = []
      for (var k = 0; k < arr.length; k++) {
        var x1 = startXGrid + k * xGridPerPoint
        var y1 = (j + 1) * this.gridLen * 4 + this.hSplitBigNum * this.gridLen * (j + 1) - (this.ppdw * arr[k]) / 100
        point.push(x1 + ',' + y1)
      }

      var pointStr = point.join(' ')
      var oPolyLine = document.createElementNS('http://www.w3.org/2000/svg', 'polyline')
      oPolyLine.setAttribute('fill', 'none')
      oPolyLine.setAttribute('points', pointStr) //设置属性，表面的是折线经过的点的位置
      oPolyLine.setAttribute('stroke', '#000') //设置图像颜色
      oPolyLine.setAttribute('stroke-width', '1')
      this.oEcg.appendChild(oPolyLine)
      // 每行的起始日期先隐藏掉
      // var date_x = startXGrid
      // var date_y = (j * 2 + 1) * this.gridLen * this.startBigGridHNum + this.hSplitBigNum * this.gridLen * (j + 1)
      // this.drawDate(date_x, date_y, parseInt(start_time) + (j * 10))

    }
  },
        
  /**
         * 画每行的起始日期
         * @param x
         * @param y
         * @param start_time
         */
  drawDate: function(x, y, start_time) {
    var time_text = this.formatDate(start_time)
    this.drawLabel(x, y + 10, 'black', 'date_' + start_time, time_text)
  },
        
  /**
         * 格式化日期
         * @param start_time
         * @returns {string}
         */
  formatDate: function(start_time) {
    function testDate(num) {
      if (num < 10) {
        num = '0' + num
      }
      return num
    }

    var upTime = start_time
    var oDate = new Date()
    oDate.setTime(upTime * 1000)
    var secondsNum = oDate.getSeconds()
    var hoursNum = oDate.getHours()
    var minutesNum = oDate.getMinutes()
    var monthNum = oDate.getMonth() + 1
    var dateNum = oDate.getDate()
    var time_text = oDate.getFullYear() + '/' + testDate(monthNum) + '/' + testDate(dateNum) + ' ' + testDate(hoursNum) + ':' + testDate(minutesNum) + ':' + testDate(secondsNum)
    return time_text
  },
        
  /**
         * 画心电图
         * @param headerData 头部文件
         * @param ecgData 心电图数据 数组 [-29, -26, -22, -29, -59, -73, -88, -103, -88, -77, -73, -51, -44, -73,....]心电电压值
         * @param start_time 检测开始时间 时间戳
         * @param sample 采样率 200/500
         */
  draw: function(headerData, ecgData, start_time, sample) {
    try {
      this.clear()
      this.drawGrid()
      this.drawSetStart('#000', 1)
      this.drawTitle(headerData)
      this.drawTimeLine('#000', 1)
      this.drawData(ecgData, start_time, sample)
    } catch (e) {
      // alert('建议使用chrome,firefox或ie9以上的浏览器')
    }
  },
        
  isChrome: function() {
    return navigator.userAgent.toLowerCase().indexOf('chrome') > -1
  },
        
  isSafari: function() {
    return navigator.userAgent.toLowerCase().indexOf('safari') > -1
  }


}
    
